package icu.lookyousmileface.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;


/**
 * @author shenj
 * @title: HttpServer1
 * @projectName NettyPro
 * @date 2020/12/5 15:57
 */
public class HttpServer1 {

    private static final int port = 2589;
    private static final EventLoopGroup mainLoop = new NioEventLoopGroup();
    private static final EventLoopGroup workerLoop = new NioEventLoopGroup();
    private static final ServerBootstrap  startServiceConfiguration = new ServerBootstrap();
    private static  ChannelFuture channelFuture = null;

    public static void main(String[] args) throws Exception {
        try {
            startServiceConfiguration.group(mainLoop, workerLoop)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast("MyHttpServerCodec",new HttpServerCodec());
                            ch.pipeline().addLast("MyHandler", new SimpleChannelInboundHandler<HttpObject>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
                                    if (msg instanceof HttpRequest){
                                        System.out.println("一个新的客户端来临:"+ctx.channel().remoteAddress());
                                        HttpRequest httpRequest = (HttpRequest)msg;
                                        URI uri = new URI(httpRequest.uri());
                                        if("/favicon.ico".equals(uri.getPath())){
                                            System.out.println("请求的资源不可达。");
                                            return;
                                        }
                                        ByteBuf dataBuf = Unpooled.copiedBuffer("<h1>世界你好！</h1>", CharsetUtil.UTF_8);
                                        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, dataBuf);
                                        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=utf-8");
                                        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, dataBuf.readableBytes());
                                        ctx.writeAndFlush(response);
                                    }
                                }
                            });
                        }
                    });

            System.out.println("Server is Ready...");

            channelFuture = startServiceConfiguration.bind(port).sync();
            channelFuture.channel().closeFuture().sync();

        }finally {
            mainLoop.shutdownGracefully();
            workerLoop.shutdownGracefully();
        }
    }
}
